﻿using System;
using System.Threading;
using MetroGA.Core;
using Windows.Storage;

namespace MetroGA.Win8.Lib
{
	internal class SessionContainer : BaseSessionContainer
	{
		private const string VisitorIdKey = "mgaVisitorId";

		private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

		private string _visitorId;
		private int _hitCount = 0;

		public SessionContainer()
		{
			try
			{
				_lock.EnterWriteLock();

				if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(VisitorIdKey))
				{
					try
					{
						_visitorId = (string)ApplicationData.Current.RoamingSettings.Values[VisitorIdKey];
					}
					catch (Exception)
					{
						_visitorId = null;
					}
				}

				if (_visitorId == null)
				{
					_visitorId = Guid.NewGuid().ToString("D");
					Save();
				}
			}
			finally
			{
				_lock.ExitWriteLock();
			}
		}

		#region Overrides of BaseSessionContainer

		public override string VisitorId
		{
			get
			{
				try
				{
					_lock.EnterReadLock();
					return _visitorId;
				}
				finally
				{
					_lock.ExitReadLock();
				}
			}
		}

		public override int IncrementHitCount()
		{
			try
			{
				return _hitCount;
			}
			finally
			{
				Interlocked.Increment(ref _hitCount);
			}
		}

		public override void Destroy()
		{
			try
			{
				_lock.EnterWriteLock();
				_visitorId = _visitorId = Guid.NewGuid().ToString("D");
				Save();
			}
			finally
			{
				_lock.ExitWriteLock();
			}
		}

		#endregion

		protected void Save()
		{
			try
			{
				_lock.EnterReadLock();
				ApplicationData.Current.RoamingSettings.Values[VisitorIdKey] = _visitorId;
			}
			finally
			{
				_lock.ExitReadLock();
			}
		}
	}
}